package mi.payment.utils.transaction;

import android.content.Context;
import android.os.RemoteException;
import android.text.TextUtils;

import com.sunmi.pay.hardware.aidl.bean.EmvTermParam;

import java.util.Map;

import mi.payment.MyApplication;
import mi.payment.bean.db.TradeData;
import mi.payment.constants.Configs;
import mi.payment.db.dao.PayDetail;
import mi.payment.settings.MerManagerSettings;
import mi.payment.settings.MerchantSettingsOperation;
import mi.payment.settings.QPSParamsOperation;
import mi.payment.settings.QPSParamsSetting;
import mi.payment.settings.SignOperation;
import mi.payment.settings.SystemParamsOperation;
import mi.payment.settings.TerminalKeyDataOperations;
import mi.payment.settings.TerminalKeyManagementBean;
import mi.payment.utils.MustParameterCalibration;
import mi.payment.utils.SystemDateTime;
import mi.payment.utils.iso8583.ImportRidAndAidParamsUtil;
import mi.payment.utils.iso8583.MsgField;
import mi.payment.utils.secure.TerminalSecure;
import sunmi.sunmiui.utils.LogUtil;

/**
 * 参数初始化Task(机具初始化、主密钥下载、终端参数下载、签到、AID下载、CAPK下载、QPS参数，卡BIN下载（BinA，BinB,黑名单）)
 *
 * @author tomcat on 2017/5/2.
 */

public class ParamsInitTask extends TransactionTask<TradeData, Void, String> {

    public static final String TAG = "ParamsInitTask";

    protected Context context = MyApplication.getInstance();

    public static boolean isChecked = false;

    protected ParamsInitTask() {
        super(MyApplication.getInstance(), false);
    }

    /**
     * 判断底层服务是否保存了IC卡参数和capk
     *
     * @return 0表示都存在; -1表示否不存在
     */
    public int checkIsExistCapkAndAID() {
        int isExistCapkAndAID = -1;
        try {
            while (MyApplication.getInstance().emvOpt == null) {
                Thread.sleep(200);
            }
            // 判断CAPK以及AID是否存在 0表示都存在; -1表示否不存在
            isExistCapkAndAID = MyApplication.getInstance().emvOpt.isExistCapkAndAID();
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return isExistCapkAndAID;
    }

    /**
     * 下载并保存IC卡参数和capk
     */
    public void downloadCapkAndAid() {
        boolean isDownloadParamsOnce = SystemParamsOperation.getInstance().isDownloadParamsOnce();
        boolean isNeedDownLoadICParams = SystemParamsOperation.getInstance().isNeedDownLoadICParams();
        if (isNeedDownLoadICParams || !isDownloadParamsOnce || checkIsExistCapkAndAID() != 0) {
            // 签到前是否下载CAPK{
            LogUtil.e(TAG, "begin download AID!");
            ICParamsDownloadTask icParamsDownloadTask = new ICParamsDownloadTask(context);
            icParamsDownloadTask.syncExecute();
            LogUtil.e(TAG, "begin download CAPK!");
            CAPKDownloadTask capkDownloadTask = new CAPKDownloadTask(context);
            capkDownloadTask.syncExecute();
            ImportRidAndAidParamsUtil.clean();
            ImportRidAndAidParamsUtil.setRIDs();
            ImportRidAndAidParamsUtil.setAIDs();
            ImportRidAndAidParamsUtil.setParam(new EmvTermParam());
            SystemParamsOperation.getInstance().saveNeedDownLoadICParams(false);

        }
        if (!isDownloadParamsOnce) {
            SystemParamsOperation.getInstance().saveDownloadParamsOnce(true);
        }
    }

    @Override
    protected String doTransactionSelf() {
        String ret = "E4";
        MerchantSettingsOperation mso = MerchantSettingsOperation.getInstance();
        MerManagerSettings managerParams = mso.getMerManagerSettings();
        int isExistCapkAndAID = checkIsExistCapkAndAID();

        boolean isDownloadParamsOnce = SystemParamsOperation.getInstance().isDownloadParamsOnce();
        // 如果商户号或者终端号为空就判断没有下载过终端参数
        // 签到前是否初始化机具
        boolean noDownloadParams = TextUtils.isEmpty(managerParams.getMerchantNum())
                || TextUtils.isEmpty(managerParams.getTerminalNum());

        if (Configs.getInstance().PARAMS_INIT_MACHINE() && (noDownloadParams || !isDownloadParamsOnce)) {
            // 签到前是否初始化机具
            LogUtil.e(TAG, "Init Machine!");
            if (Configs.getInstance().INIT_SAVE_KEK()) {
                String kek = Configs.getInstance().KEK();
                int saveResult = TerminalSecure.saveKEK(kek);
                if (saveResult != 0) {
                    return ret;
                }
            }
            InitMachineTask initMachineTask = new InitMachineTask(context);
//            ret = initMachineTask.syncExecute();
//            if (!TextUtils.equals("00", ret)) {
//                return ret;
//            }
        }
        if (!noDownloadParams) {
            LogUtil.e(TAG, "Machine info already exist");
        }

        // 签到前是否下载主密钥
        TerminalKeyManagementBean tkmBean = TerminalKeyDataOperations.getInstance().getTerminalKeyManagementBean();
        boolean noDownloadTMK = tkmBean == null || !tkmBean.isHasDownloadTMK();

        if (Configs.getInstance().PARAMS_INIT_TMK_DOWNLOAD() && (noDownloadTMK || !isDownloadParamsOnce)) {
            // 签到前是否下载主密钥
            LogUtil.e(TAG, "TMK Download！");
            TMKDownloadTask task = new TMKDownloadTask(context);
            ret = task.syncExecute();
            if (!TextUtils.equals("00", ret)) {
                return ret;
            }
        }
        if (!noDownloadTMK) {
            LogUtil.e(TAG, "TMK Already exist");
        }

        // 签到前是否下载终端参数
        if (Configs.getInstance().PARAMS_INIT_TP_DOWNLOAD()) {
            MerchantParamsDownloadTask task = new MerchantParamsDownloadTask(context);
            ret = task.syncExecute();
            if (!TextUtils.equals("00", ret)) {
                return ret;
            }
        }


        // 签到前是否上送终端状态
        if (Configs.getInstance().PARAMS_INIT_STATE_UPLOAD()) {
            // TODO
        }

        // 参数校验
        if (Configs.getInstance().IS_TPDU() && !MustParameterCalibration.canToNext()) {
            ret = "E5";
            return ret;
        }
        if (!Configs.getInstance().IS_TPDU() && !MustParameterCalibration.canToNext5()) {
            ret = "E5";
            return ret;
        }

        TradeData tradeData = params[0];
        PayDetail payDetail = tradeData.getPayDetail();
        managerParams = mso.getMerManagerSettings();
        payDetail.setTerminalNo(managerParams.getTerminalNum());
        payDetail.setMerchantNo(managerParams.getMerchantNum());
        // 签到
        SignTask signTask = new SignTask(context);
        ret = signTask.syncExecute(params);
        if (!TextUtils.equals("00", ret)) {
            return ret;
        }
        LogUtil.e(TAG, "Sign Success!");

        // 签到后是否要做处理要求
        if (Configs.getInstance().AFTER_SIGNTASK_PROCESSR_EQUIRE()) {
            if (signTask.getProcessCode() != -1) {
                ProcessRequireManager.syncCheckProcessCode(signTask.getProcessCode());
            }
        }

        //签到后是否下载双免参数
        if (Configs.getInstance().PARAM_INIT_QPS_BIN_DOWNLOAD()) {
            QpsDownloadTask task = new QpsDownloadTask(context);
            ret = task.syncExecute();
            if (!TextUtils.equals("00", ret)) {
                return ret;
            }

            QPSParamsSetting setting = QPSParamsOperation.getInstance().getQPSParamsSettings();
            String cardBinB = setting.getCardBinB();
            if (TextUtils.isEmpty(cardBinB)) {
                CardBinDownloadTask taskB = new CardBinDownloadTask(context);
                taskB.initBinBParams();
                //下载卡BINB
                ret = taskB.syncExecute();
                if (!TextUtils.equals("00", ret)) {
                    return ret;
                }
                CardBinDownloadTask taskC = new CardBinDownloadTask(context);
                taskC.initBinCParams();
                //下载卡BINC(黑名单)
                ret = taskC.syncExecute();
                if (!TextUtils.equals("00", ret)) {
                    return ret;
                }
            }
        }


        boolean isNeedDownLoadICParams = SystemParamsOperation.getInstance().isNeedDownLoadICParams();
        if (isNeedDownLoadICParams || !isDownloadParamsOnce || isExistCapkAndAID != 0) {
            if (Configs.getInstance().PARAMS_INIT_AID_DOWNLOAD()) {
                LogUtil.e(TAG, "begin download AID!");
                ICParamsDownloadTask task = new ICParamsDownloadTask(context);
                String result = task.syncExecute();
                // if (TextUtils.equals("00", result)) {
                ImportRidAndAidParamsUtil.setAIDs();
                // }
            }
            // 签到前是否下载CAPK
            if (Configs.getInstance().PARAMS_INIT_CAPK_DOWNLOAD()) {
                LogUtil.e(TAG, "begin download CAPK!");
                CAPKDownloadTask task = new CAPKDownloadTask(context);
                String result = task.syncExecute();
                // if (TextUtils.equals("00", result)) {
                ImportRidAndAidParamsUtil.setRIDs();
                // }
            }
            SystemParamsOperation.getInstance().saveNeedDownLoadICParams(false);
        }
        if (!isDownloadParamsOnce) {
            SystemParamsOperation.getInstance().saveDownloadParamsOnce(true);
        }

        if (TextUtils.equals("00", ret)) {
            // 保存签到时间
            int time = SystemDateTime.getCurrentYYYYMMDD();
            SignOperation.getInstance().saveLastSignTime(time);
            ParamsInitTask.isChecked = true;
        }
        return ret;
    }

    @Override
    protected void onBegin(TradeData[] params) {
    }

    @Override
    protected String appointResult() {
        return resultStr;
    }

    @Override
    protected Map<String, MsgField> preAssembly() {
        return null;
    }

    @Override
    protected byte[] changeAndAssembly(Map<String, MsgField> fieldMap) {
        return null;
    }


}
